<script setup lang="ts" name="SystemRoleAssignUserForm">
import { storeToRefs } from 'pinia'
import { useAppStoreWithOut } from '@/store/modules/app'
import { RoleType } from '@/api/system/role'
import { PermitApi, PermissionAssignRoleUserReqType } from '@/api/system/permit'
import { UserApi, UserType } from '@/api/system/user'
const appStore = useAppStoreWithOut()
const { systemConfig } = storeToRefs(appStore)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用checkedParentIdList: [],
const formData: any = ref({
  roleId: undefined as number | undefined,
  name: '',
  userIds: []
})
const formRef = ref() // 表单 Ref
const userList = ref<UserType[]>([]) // 菜单树形结构
/** 打开弹窗 */
const open = async (row: RoleType) => {
  visible.value = true
  resetForm()
  // 设置数据
  formData.value.roleId = row.id
  formData.value.name = row.name
  formLoading.value = true
  try {
    userList.value = await UserApi.getUserByUser()
    formData.value.userIds = await PermitApi.Search.roleUserList(row.id!)
  } finally {
    formLoading.value = false
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 提交表单
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as PermissionAssignRoleUserReqType
    await PermitApi.Assign.roleUser(data)
    message.success(t('message', 'updateSuccess'))
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  // 重置选项
  // 重置表单
  formData.value = {
    roleId: undefined,
    name: '',
    userIds: []
  }
  formRef.value?.resetFields()
}
</script>

<template>
  <Dialog v-model="visible" title="分配用户" width="720">
    <el-form ref="formRef" v-loading="formLoading && systemConfig.loadingType === 'module'" :model="formData" label-width="80px">
      <el-form-item :label="t('sys.role', 'name')">
        <el-tag>{{ formData.name }}</el-tag>
      </el-form-item>
      <el-form-item label="分配用户">
        <el-select v-model="formData.userIds" clearable multiple filterable placeholder="请选择用户">
          <el-option v-for="user in userList" :key="user.id" :label="user.nickname" :value="user.id!" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">{{ t('action', 'cancel') }}</el-button>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">{{ t('action', 'confirm') }}</el-button>
    </template>
  </Dialog>
</template>

<style scoped lang="scss"></style>
